package com.xiaoxu.privatechat.config;

import com.xiaoxu.privatechat.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xiaoxu
 * @version 1.0
 * @description TODO
 * @date 2023/2/19 18:58
 */
@Configuration
public class IpFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(IpFilter.class);
    @Resource
    private RestTemplate restTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("初始化ip过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("FilterIP 过滤器执行过滤方法");
        // 得到请求的IP地址 和要过滤的Ip地址进行对比
        String ip = IpUtil.getIpAddr(request);
        String url = "http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true";
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        String body = entity.getBody();

        System.err.println(body);
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        log.info("销毁ip过滤器");
    }
}
